<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Express Demo</title>
        <link rel="stylesheet" href="/public/style.css" />
    </head>

    <body>
        <main>
            <h1>Hello alice</h1>

            <nav>
                <ul class="links">
                    <li><a href="/about">about</a></li>
                </ul>
            </nav>

            <button onclick="getUser()">getUser</button>

            <button onclick="getBook()">getBookList</button>

            <section class="create">
                <div class="input-inline">
                    <label for="title">title</label>
                    <input id="title" value="machine learning" />
                </div>
                <div class="input-inline">
                    <label for="author">author</label>
                    <input type="text" id="author" value="Lucy" />
                </div>
                <button onclick="postBook()">postBook</button>
            </section>

            <section class="search">
                <input id="kw" />
                <button onclick="searchBook()">bookSearch</button>
            </section>

            <textarea rows="6" id="output"></textarea>

            <div class="table-wrap"></div>
        </main>

        <script>
            function output(con) {
                document.querySelector("#output").innerHTML =
                    typeof con === "string " ? con : JSON.stringify(con);
                return con;
            }

            function getUser() {
                fetch("/user" + "?t=" + Date.now())
                    .then((res) => res.text())
                    .then(output);
            }

            function $(id) {
                return document.getElementById(id);
            }
            function postBook() {
                const title = $("title").value;
                const author = $("author").value;

                fetch("/book", {
                    headers: {
                        "content-type": "application/json",
                    },
                    method: "POST",
                    body: JSON.stringify({
                        title,
                        author,
                    }),
                })
                    .then((res) => res.text())
                    .then(output)
                    .then(getBook);
            }

            function getBook() {
                fetch("/book/list", { method: "GET" })
                    .then((res) => res.text())
                    .then(output)
                    .then(renderTable);
            }

            function renderTable(data) {
                if (!data.length) return data;
                if (typeof data === "string") {
                    data = JSON.parse(data);
                }

                bookList = data;

                const rows = data;
                const cols = Object.keys(rows[0]);
                cols.push("action");

                const headRowHtml = cols
                    .map((col) => `<th>${col}</th>`)
                    .join("");
                const rowHtml = (row, index) => {
                    const vals = Object.values(row);
                    const actionVal = (row) => {
                        return `<button data-id="${row.id}" data-index="${index}" onclick="updateBook(${index})">update</button>
            <button data-id="${row.id}" data-index="${index}" onclick="delBook(${row.id})">del</button>`;
                    };
                    vals.push(actionVal(row));

                    const tds = vals
                        .map((val, i) => {
                            const key = cols[i];
                            let tdHtml = "";
                            if (key === "id" || key === "action") {
                                tdHtml = val;
                            } else {
                                tdHtml = `<input value="${val}" class="val-input" data-key="${key}" data-index="${index}" onchange="changeValue('${key}', ${index}, event)"  />`;
                            }

                            return `<td>${tdHtml}</td>`;
                        })
                        .join("");

                    return `<tr>${tds}</tr>`;
                };
                const bodyHtml = rows.map(rowHtml).join("\n");

                const tblHtml = `
            <table>
                <thead>
                    <tr>${headRowHtml}</tr>
                </thead>
                <tbody>
                    ${bodyHtml}
                </tbody>
            </table>
            `;

                document.querySelector(".table-wrap").innerHTML = tblHtml;

                return data;
            }

            function searchBook() {
                const titleKw = document.querySelector("#kw").value;
                fetch(`/book/search?title=${titleKw}`)
                    .then((res) => res.json())
                    .then(output)
                    .then(renderTable);
            }

            function updateBook(index) {
                const book = bookList[index];
                fetch("/book/update", {
                    method: "POST",
                    body: JSON.stringify(book),
                    headers: {
                        "content-type": "application/json",
                    },
                })
                    .then((res) => res.text())
                    .then(output);
            }

            function delBook(id) {
                fetch(`/book/del?id=${id}`)
                    .then((res) => res.json())
                    .then(output)
                    .then(getBook);
            }

            function changeValue(key, index, event) {
                const book = bookList[index];
                book[key] = event.target.value;
                console.log("🚀 ~ changeValue ~ bookList:", bookList);
            }

            var bookList = [];
        </script>
    </body>
</html>
